package com.cyan.teamquestionnaire.mappers;

import com.cyan.teamquestionnaire.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface UserMapper {

    @Select("select * from user_table where name = #{name}")
    User selectByName(String name);

    @Select("select * from user_table where tel = #{tel}")
    User selectByTel(String tel);

    //只返回租户的信息！！！！！！！！！！！！！
    @Select("select * from user_table where level = 2 and user_table.name like #{query}")
    List<User> selectAllTenantAndUser(String query);

    // 查询user群组，用于用户的删除，修改，感觉修改应该被运许，删除不被允许
    @Select("select count(*) from groups where user_name = #{name} or tenant_name = #{name} limit 1")
    int selectCountGroup(String name);

    // 创建用户
    @Insert("insert into user_table(level, name, passwd, tel,count) values(#{level},#{name},#{passwd},#{tel},#{count})")
    void createUser(User u);

    // 查找自己管理的用户，从群组中查找
    @Select("select u.`level`, u.`name`, u.passwd, u.tel from user_table as u , " +
            "(select DISTINCT g1.tenant_name,  g2.user_name from groups as g1, group_user as g2 where g1.gid = g2.gid) as r\n" +
            "where u.`name` = r.user_name and r.tenant_name = #{name} and u.name like #{query};")
    List<User> getManagedUsers(@Param("name") String name, @Param("query") String query);

    // 修改用户
    @Update("update user_table set level = #{level}, passwd = #{passwd}, count = #{count} where name = #{name}")
    int modifyUser(User u);


    // 修改用户手机号
    @Update("update user_table set tel = #{tel} where name = #{name}")
    int modifyUserTel(User u);

  //删除时候进行判断，如果是管理员删除租户，那么需要判断群组，如果删除用户直接删除
    @Delete("delete from user_table where name = #{name}")
    void deleteUser(User u);

    //查询租户创建的用户，模糊查询
    @Select("select user_name from tenant_user where tenant_name = #{name} and user_name like #{query}")
    List<String> tenantCreateUser(@Param("name")String name, @Param("query") String query);

    //租户创建用户加入表中
    @Insert("insert into tenant_user(tenant_name, user_name) values(#{tenantName},#{userName})")
    int tenantAddUser(@Param("tenantName")String tenantName,@Param("userName") String userName);

    //删除用户的时候同时要删除用户和租户的关系表
    @Delete("delete from tenant_user where user_name = #{userName}")
    int tenantDelteUser(@Param("userName")String userName);

    //返回所有的答者  level==4的成员
    @Select("select * from user_table where level = 4 and name like #{query}")
    List<User> selectAllAnswerer( @Param("query") String query);

    //通过答者列表进行租户管理用户的增添
    @Update("update user_table set level = 3 ,count = #{count} where name = #{userName} ")
    int tenantCreateUserByAnsList(@Param("userName") String userName,@Param("count") int count);

    //获得用户的租户人是谁
    @Select("select tenant_name from tenant_user where user_name = #{name}")
    String getUserForTenant(String name);
}
